import { app, BrowserWindow, Tray, Menu } from "electron";
import { getMainWindow } from "./windows";
import type { MenuOptions } from "./types";

declare type TrayManager = {
    tray: Tray | undefined;
};

const trayM: TrayManager = {
    tray: undefined,
};

const trayProxy = new Proxy(trayM, {
    get: function (obj: TrayManager, prop: string) {
        return obj[prop];
    },
    set: function (obj: TrayManager, prop: string, value: any) {
        if (obj[prop]) {
            return false;
        }
        obj[prop] = value;
        return true;
    },
});

/**
 * 创建托盘图标
 * @param iconPath 图标文件目录
 * @param menu 菜单选项
 * @param click 控制是否启用默认点击事件。单击默认启用，对应的事件为显示主窗口。双击默认关闭，对应事件为显示所有窗口。
 * @returns 托盘图标实例对象
 */
function createTray(
    iconPath: string,
    menu: MenuOptions,
    click: { click: "show-main" | boolean; double: "show-all" | boolean } = {
        click: "show-main",
        double: false,
    }
) {
    let tray = new Tray(iconPath);
    tray.setContextMenu(Menu.buildFromTemplate(menu));
    if (["show-main", true].includes(click.click)) {
        tray.on("click", () => {
            const mainWindow = getMainWindow();
            mainWindow.show();
        });
    }
    if (["show-all", true].includes(click.double)) {
        tray.on("double-click", () => {
            const wins = BrowserWindow.getAllWindows();
            for (const win of wins) {
                win.show();
            }
        });
    }
    trayProxy.tray = tray;
    return tray;
}

function getTray() {
    return trayProxy.tray;
}

export { createTray, getTray };
